package com.syh.appshare;



import java.util.ArrayList;
import java.util.List;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TabHost;

import com.syh.appshare.common.utils.LogUtil;
import com.syh.appshare.modules.news.NewsActivity;
import com.syh.appshare.services.ShareServices;

public class MainActivity extends TabActivity {
    
	public final String tag="main";
	
	public static MainActivity instance;
	public TabHost tabHost;
	
	
	/**
     * 保存tabActivity中activity标签
     */
    private List<String> tabList=new ArrayList<String>();
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        initActivity();
    }
    
    private void initActivity(){
    	//启动服务
    	startService(new Intent(this,ShareServices.class));
    	
    	instance=MainActivity.this;
    	tabHost=getTabHost();
    	Intent intent=new Intent(MainActivity.this,NewsActivity.class);
    	setCrurentTab("SourceCatalog", intent);
    	try {
    		//隐藏标签栏
			getTabWidget().setVisibility(View.GONE);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    public void setCrurentTab(String tabSpec,Intent intent){
		if(!tabList.contains(tabSpec)){
			 tabHost.addTab(tabHost.newTabSpec(tabSpec)
			            .setIndicator(tabSpec, getResources().getDrawable(R.drawable.icon))
			            .setContent(intent));
			 tabList.add(tabSpec);
		}
		
		tabHost.setCurrentTabByTag(tabSpec);
    }

	@Override
	protected void onDestroy() {
		super.onDestroy();
		instance=null;
	}
	
	/**
	 * 返回当前tab标签的前一个标签
	 * @return @return true:返回成功  false:返回失败
	 * @author wangweiwei
	 * 2012-3-15
	 */
	public boolean backPrevTab() {
		if(tabList.size()>1) {
			tabList.remove(tabList.size()-1);
			tabHost.setCurrentTabByTag(tabList.get(tabList.size()-1));
			return true;
		}
		
		return false;
	}
    
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		LogUtil.debug(tag, "MainActivity onKeyDown.");
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		LogUtil.debug(tag, "MainActivity onKeyUp.");
		if(keyCode==KeyEvent.KEYCODE_BACK ){		
			if(goBack()){
				LogUtil.debug(tag, "goBack is true");
				return true;
			}else{
				LogUtil.debug(tag, "goBack is false");
				finish();
			}
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}
	
	/**
	 * 是否消耗掉返回事件
	 * @return
	 */
	private boolean goBack(){
		return backPrevTab();
	}
}